<?php

class User_Document_User extends Mongo_Document
{

	protected $_name = 'users';

	/**
	 * @return string
	 */
	public function getTitle()
	{
		return $this -> name;
	}

	/**
	 * @return string
	 */
	public function __toString()
	{
		return $this -> name;
	}

	/**
	 * @return string
	 */
	public function getUrl()
	{
		return 'user/' . $this -> _id;
	}

	/**
	 * @return string
	 */
	public function getPhoto()
	{
		return 'user/photo';
	}

	/**
	 * set password
	 * @param string $string
	 * @return Document_User
	 *
	 */
	public function setPassword($string)
	{
		$this -> salt = Text::random(8);
		$this -> password = $this -> _createPassword($string, $this -> salt);
		return $this;
	}

	/**
	 * is valid password
	 * @param string $string
	 * @return bool
	 *
	 */
	public function isPassword($string)
	{
		return $this -> _createPassword($string, $this -> salt) == $this -> password;
	}

	/**
	 * @return string
	 */
	protected function _createPassword($string, $salt)
	{
		return sha1($string . $salt, false);
	}

	/**
	 * @return true/false
	 */
	public function login()
	{
		$this -> login_ip = Request::initiator() -> getClientIp();
		$this -> login_at = time();
		$this -> save();

		// setup cookie
		$_SESSION['uid'] = $this -> _id;

		return true;
	}

	/**
	 * @return bool
	 */
	public function isSuper()
	{
		return ($this -> level_id and $this -> level_id < 2);
	}

	/**
	 * @return bool
	 */
	public function isAdmin()
	{
		return ($this -> level_id and $this -> level_id < 3);
	}

	/**
	 * @return bool
	 */
	public function isModerator()
	{
		return ($this -> level_id and $this -> level_id < 4);
	}

	/**
	 * @return bool
	 */
	public function isEditor()
	{
		return ($this -> level_id and $this -> level_id < 5);
	}

	/**
	 * @return bool
	 */
	public function isMember()
	{
		return $this -> level_id and $this -> level_id < 6;
	}

	/**
	 * @return bool
	 */
	public function isVerified()
	{
		return $this -> is_verified;
	}

	/**
	 * @return bool
	 */
	public function isApproved()
	{
		return $this -> is_approved;
	}

	/**
	 * @return bool
	 */
	public function isActive()
	{
		return $this -> is_active;
	}

}
